package com.tg.base.concurrent.thread;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * 验证sync下，线程不可中断
 * 输出结果：
 * --------------------
 * 开始同步块:f1
 * 开始同步块:f2
 * f2取消
 * 结束同步块:f1
 * 结束同步块:f2
 * --------------------
 * 即使f2取消，但f2仍然会阻塞到f1完成，并完成自己
 *
 */
public class ThreadCannotInterruptWithSynchronized {

    private static ArrayList<Integer> objects = Lists.newArrayList();
    private static ArrayList<Integer> results = Lists.newArrayList();

    public static void main(String[] args) throws InterruptedException {

        FutureTask f1 = build("f1");
        FutureTask f2 = build("f2");

        Executor executorService = Executors.newFixedThreadPool(3);
        executorService.execute(f1);
        executorService.execute(f2);

        TimeUnit.SECONDS.sleep(3);

        f2.cancel(true);
        System.out.println("f2取消");
    }

    private static FutureTask build(final String name) {
        return new FutureTask(() -> {
            System.out.println("开始同步块:" + name);
            synchronized (objects) {
                slowAction();
            }
            System.out.println("结束同步块:" + name);
            return 0;
        });
    }

    /**
     * 慢操作，同时
     */
    private static int slowAction() {
        for (int i = 0; i < 100000; i++) {
            objects.add(i);
            int t = 5 * i;
            if (objects.contains(t)) {
                results.add(t);
            }
        }
        return 0;
    }


}
